# -*- coding: utf-8 -*-
# @Author: liuzhen
# @Date:   2018-07-18 13:01:36
# @Last Modified by:   liuzhen
# @Last Modified time: 2018-07-19 10:13:08
import sys  
import maya.OpenMayaUI as omUI  
from PySide2 import QtUiTools, QtCore, QtWidgets, QtGui  
from PySide2.QtCore import *  
from PySide2.QtWidgets import *  
from PySide2.QtGui import *  

import pyside2uic as pysideuic  
import shiboken2  
import os  
import logging  
import xml.etree.ElementTree as xml  
from cStringIO import StringIO  
import pymel.core as pmc
import maya.cmds as cmds
import ScriptActions as SA
reload(SA)
try :  
    pmc.loadPlugin('mtoa', quiet=True)
except :  
    pass
try :     
    pmc.loadPlugin('xgenToolkit', quiet=True)
except :  
    pass

dir_path = os.path.dirname(__file__)
ui_file = os.path.join(dir_path, "output.ui")
X = os.sep
print ui_file

def getMayaWindow() :  
    ptr = omUI.MQtUtil.mainWindow()  
    return shiboken2.wrapInstance(long(ptr), QMainWindow)  



def loadUiType(uiFile):
    """
    :author: Jason Parks
    Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first
    and then execute it in a special frame to retrieve the form_class.
    """
    parsed = xml.parse(uiFile)
    widget_class = parsed.find('widget').get('class')
    form_class = parsed.find('class').text

    with open(uiFile, 'r') as f :  
        o = StringIO()  
        frame = {}  

        pysideuic.compileUi(f, o, indent=0)  
        pyc = compile(o.getvalue(), '<string>', 'exec')  
        exec pyc in frame  

        # Fetch the base_class and form class based on their type in the xml from designer
        form_class = frame['Ui_%s' % form_class]  
        base_class = getattr(QtWidgets, widget_class)  
    return form_class, base_class  


FormClass, BaseClass = loadUiType(ui_file)  


class aaa(FormClass, BaseClass) : 
    def __init__(self, parent=getMayaWindow()) :  
        self.labelText = "Name:%s\nDate Created:%s\nDate Modified:%s\n" %("unknown","unknown","unknown")
        self.asset_dict = {}
        self.xgen_dict = {}
        self.all_hair_mat = {}
        self.basepath = ""
        self.baseimportpath = ""
        super(aaa, self).__init__(parent)  
        self.setupUi(self)  
        self.setWindowTitle("Asset export import")
        self.refresh()
        self.Frange_groupbox.setVisible(False)
        self.exportSelection_radiobutton.setChecked(True)  
        self.refresh_pushbutton.clicked.connect(self.refresh)  
        self.export_pushbutton.clicked.connect(self.button_slot)
        self.regExp = QRegExp('[0-9]{0,5}')  
        self.filedlg = file_dialog("Set output path")
        self.import_filedlg = file_dialog("Get input path")
        self.info_label.setText(self.labelText)

        self.start_lineEdit.setValidator(QRegExpValidator(self.regExp,self))  
        self.end_lineEdit.setValidator(QRegExpValidator(self.regExp,self))  

        self.output_pushButton.clicked.connect(self.chooseDir)
        self.exportMaterial_pushbutton.clicked.connect(self.xxxxx)
        self.browse_pushbutton.clicked.connect(self.chooseInDir)
        self.file_listwidget.itemClicked.connect(self.setDirinfo)
        self.test.clicked.connect(self.showDir)
        self.test_pb.clicked.connect(self.test_print)

    def showDir(self) :  
        directoryx = self.im_lineedit.text()
        selected_item = self.file_listwidget.selectedItems()  
        if selected_item == [] :  
            pass  
        else :  
            baseDir = directoryx + X + selected_item[0].text()  
            importdir = SA.importer(baseDir)  
            # importdir.showDir()  
            importdir.import_all()


    def set_assetdict(self) :  
        self.asset_dict = SA.getall_transformNode()  

    def chooseDir(self) :  
        self.basepath = self.filedlg.getExistingDirectory()
        self.output_lineEdit.setText("%s" % (self.basepath))

    def chooseInDir(self) :  
        self.baseimportpath = self.import_filedlg.getExistingDirectory()
        self.im_lineedit.setText("%s" % (self.baseimportpath))
        xlistdir = os.listdir(self.baseimportpath)
        self.file_listwidget.clear()
        for d in xlistdir :  
            file_item = QListWidgetItem(self.file_listwidget)  
            file_item.setText(d)

    def setDirinfo(self) :  
        selected_item = self.file_listwidget.selectedItems()
        if selected_item == [] :  
            self.info_label.setText(self.labelText)
        else :  
            item_name = selected_item[0].text()
            full_path = self.baseimportpath+X+item_name  
            solver = SA.fileSolver(full_path)
            info_dict = solver.getFileinfo()
            info_string = "Name:%s\nDate Created:%s\nDate Modified:%s\n" %(info_dict["name"], 
                                                                           info_dict["create_time"], 
                                                                           info_dict["change_time"])
            self.info_label.setText(info_string)

    def xxxxx(self) :  
        material_dict = self.xgen_dict
        SA.export_material(self.basepath, material_dict)

    def refresh(self) :  
        self.set_assetdict()
        # self.exportSelection_radiobutton.setChecked(True)
        self.all_hair_mat
        self.all_hair_mat.clear()

        # self.all_hair_mat = SA.get_hair_material()
        
        self.camera_listwidget.clear()  
        self.model_listwidget.clear()  
        self.prop_listwidget.clear()
        self.xgen_listwidget.clear()  


        for c_node in self.asset_dict["char"] :  
            c_model_item = QListWidgetItem(self.model_listwidget)  
            c_model_item.setSizeHint(QSize(90, 34))  
            self.cmodellist_iterm = list_iterm("%s" % (c_node.name()), "model")  
            self.model_listwidget.setItemWidget(c_model_item, self.cmodellist_iterm)  
        for p_node in self.asset_dict["prop"] :  
            p_model_item = QListWidgetItem(self.prop_listwidget)  
            p_model_item.setSizeHint(QSize(90, 34))  
            self.pmodellist_iterm = list_iterm("%s" % (p_node.name()), "prop")  
            self.prop_listwidget.setItemWidget(p_model_item, self.pmodellist_iterm)  
        for cam_node in self.asset_dict["camera"] :  
            cam_model_item = QListWidgetItem(self.camera_listwidget)  
            cam_model_item.setSizeHint(QSize(90, 34))  
            self.cam_modellist_iterm = list_iterm("%s" % (cam_node.name()), "cam")  
            self.camera_listwidget.setItemWidget(cam_model_item, self.cam_modellist_iterm)  


        self.xgen_dict = SA.get_xgen_dict()

        for key in self.xgen_dict :  
            xgen_item = QListWidgetItem(self.xgen_listwidget)  
            xgen_item.setSizeHint(QSize(90, 34))
            self.xgenlist_iterm = list_iterm("%s" % (pmc.PyNode(key).name()), "shader")  
            self.xgen_listwidget.setItemWidget(xgen_item, self.xgenlist_iterm)

    def test_print(self) :  
        xxxgen_list = SA.xgen_old_exist(self.xgen_dict)
        print xxxgen_list
        print "+++++++++++++@@@@@@@@@@@@++++++++++@@@@@@@@@@@"


    def export_selected_cam(self) : 
        all_camitemlist = [i for i in self.camera_listwidget.findChildren(QCheckBox)]
        s_camitemlist = [c for c in all_camitemlist if c.checkState() == 2  
                                                    and c.objectName().split("_")[-1] == "cb"]  
        if s_camitemlist == [] :  
            print "no camera is selected"  
            pass  
        else :  
            for cam in s_camitemlist :  
                cam_attr = self.get_attr(cam)  
                cameranode = SA.nodeControl(pmc.PyNode(cam_attr[0]))  
                cameranode.export_cam(cam_attr[1],  
                                      cam_attr[2],  
                                      cam_attr[3],  
                                      self.basepath)  

    def export_selected_abc(self) :  
        all_modelitemlist = [i for i in self.model_listwidget.findChildren(QCheckBox)]  
        cb_lst = [i for i in all_modelitemlist  
            if i.objectName().split("_")[-1] == "cb"]  
        s_modelitemlist = [c for c in cb_lst if c.checkState() == 2 ]  

        if self.exportAll_radiobutton.isChecked() :  
            for model in all_modelitemlist :  
                mode_attr = self.get_attr(model)
                modelnode = SA.nodeControl(pmc.PyNode(mode_attr[0]))  
                modelnode.exportAbc(mode_attr[1],  
                                    mode_attr[2],  
                                    mode_attr[3],  
                                    self.basepath,  
                                    mode_attr[4].isChecked())  
        elif self.exportSelection_radiobutton.isChecked() :  
            print s_modelitemlist  
            if s_modelitemlist ==[] :  
                print "no module is selected"  
                pass
            else :  
                for model in s_modelitemlist :  
                    mode_attr = self.get_attr(model)
                    modelnode = SA.nodeControl(pmc.PyNode(mode_attr[0]))  
                    modelnode.exportAbc(mode_attr[1],  
                                        mode_attr[2],  
                                        mode_attr[3],  
                                        self.basepath,  
                                        mode_attr[4].isChecked())  

    def export_prop_abc(self) :  
        all_propitemlist = [i for i in self.prop_listwidget.findChildren(QCheckBox)]  
        cb_lst = [i for i in all_propitemlist  
            if i.objectName().split("_")[-1] == "cb"]
        print cb_lst
        s_propitemlist = [c for c in cb_lst if c.checkState() == 2 ]  

        if self.exportAll_radiobutton.isChecked() :  
            for cb in s_propitemlist :  
                mode_attr = self.get_attr(cb)
                modelnode = SA.nodeControl(pmc.PyNode(mode_attr[0]))  
                modelnode.export_prop_abc(mode_attr[1],  
                                          mode_attr[2],  
                                          mode_attr[3],
                                          self.basepath)  
        elif self.exportSelection_radiobutton.isChecked() :  
            print s_propitemlist
            if s_propitemlist ==[] :  
                print "no Pmodule is selected"
                pass
            else :  
                for model in s_propitemlist :  
                    mode_attr = self.get_attr(model)
                    modelnode = SA.nodeControl(pmc.PyNode(mode_attr[0]))  
                    modelnode.export_prop_abc(mode_attr[1],  
                                              mode_attr[2],  
                                              mode_attr[3],
                                              self.basepath)  

#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@---------------+++++++++++++++++++++

    def export_selected_xgen(self) :  

        all_xgenitemlist = [i for i in self.xgen_listwidget.findChildren(list_iterm)]
        s_xgenshaderitem = [i for i in all_xgenitemlist if i.checkbox.checkState() == 2]
        print all_xgenitemlist
        # s_xgenitemlist = [c.text() for c in all_xgenitemlist if c.checkState() == 2 ]  

        if self.exportAll_radiobutton.isChecked() :  
            all_SG_typelist = [pmc.PyNode(x.name).type() for x in all_xgenitemlist]  
            all_xgen_typelist = [x.type() for i in all_SG_typelist for x in i.listConnections(type = ["xgmSplineDescription", "xgmDescription"], sh=True)]
            print all_xgen_typelist
            print "@_@_@_@_@_@_@_@_@_@_@_@_@_@_@_@_@_@_@"
            if "xgmDescription" in all_xgen_typelist :  
                SA.nodeControl.old_xgen2patches()  
            else :  
                pass
            for xgen in all_xgenitemlist :  
                xgen_attr = self.get_attr_up(xgen)
                print self.xgen_dict[xgen_attr[0]]  

                xgennode = self.xgen_dict[xgen_attr[0]]  

                SA.nodeControl.export_xgen(xgennode, 
                                           xgen_attr[1],
                                           xgen_attr[2],
                                           xgen_attr[3],
                                           xgen_attr[0],
                                           self.basepath)
        elif self.exportSelection_radiobutton.isChecked() :  
            if len(s_xgenshaderitem) :  
                s_SG_typelist = [pmc.PyNode(x.name) for x in s_xgenshaderitem]
                s_xgen_typelist = [x.type() for i in s_SG_typelist for x in i.listConnections(type = ["xgmSplineDescription", "xgmDescription"], sh=True)]
                print s_xgen_typelist
                print "@_@_@_@_@_@_@_@_@_@_@_@_@_@_@_@_@_@_@"
                if "xgmDescription" in s_xgen_typelist :  
                    SA.nodeControl.old_xgen2patches()  
                else :  
                    pass  
                for xgen in s_xgenshaderitem :  
                    xgen_attr = self.get_attr_up(xgen)
                    xgennode = self.xgen_dict[xgen_attr[0]]
                    if xgennode is None :  
                        pass
                    else :  
                        SA.nodeControl.export_xgen(xgennode, 
                                                   xgen_attr[1],
                                                   xgen_attr[2],
                                                   xgen_attr[3],
                                                   xgen_attr[0],
                                                   self.basepath)
        

    def button_slot(self) :  
        SA.get_nodeInfo(self.basepath, self.asset_dict)
        self.export_selected_abc()
        self.export_prop_abc()
        self.export_selected_cam()
        SA.get_nodeInfo(self.basepath, self.asset_dict)
        SA.export_reference_list(self.basepath)
        self.export_selected_xgen()  

        # for vis in self.asset_dict["vis"] :  
        #     if pmc.PyNode(vis).hasAttr("Xgen") :  
        #         print vis
        #         vis_attr = pmc.Attribute('%s.Xgen'%(vis))
        #         try :  
        #             vis_attr.disconnect(inputs=True)
        #         except : 
        #             pass
        #         pmc.PyNode(vis).setAttr("Xgen", 1)
        #     elif pmc.PyNode(vis).hasAttr("xgen") :  
        #         print vis
        #         vis_attr = pmc.Attribute('%s.xgen'%(vis))
        #         try :  
        #             vis_attr.disconnect(inputs=True)
        #         except :  
        #             pass
        #         pmc.PyNode(vis).setAttr("xgen", 1)


            # if not pmc.Attribute('%s.Xgen'%(vis))  :  
            #     vis_attr.Attribute('%s.Xgen'%(vis))
            #     try :  
            #         vis_attr.disconnect(inputs=True)
            #     except :  
            #         pass
            #     pmc.PyNode(vis).setAttr("Xgen", True)

        # self.export_selected_xgen()  

        for vis in self.asset_dict["vis"] :  
            if pmc.PyNode(vis).hasAttr("Xgen") :  
                print vis
                vis_attr = pmc.Attribute('%s.Xgen'%(vis))
                try :  
                    vis_attr.disconnect(inputs=True)
                except : 
                    pass
                pmc.PyNode(vis).setAttr("Xgen", 0)
            elif pmc.PyNode(vis).hasAttr("xgen") :  
                print vis
                vis_attr = pmc.Attribute('%s.xgen'%(vis))
                try :  
                    vis_attr.disconnect(inputs=True)
                except :  
                    pass
                pmc.PyNode(vis).setAttr("xgen", 0)

    def get_attr(self, checkbox) :  
        parent = checkbox.parent()
        object_name = parent.name
        print object_name
        object_bool = parent.findChild(QCheckBox, "%s_rc" % (object_name))  
        print object_bool
        object_sf = parent.findChild(QLineEdit, "%s_sf" % (object_name))  
        print object_sf
        object_ef = parent.findChild(QLineEdit, "%s_ef" % (object_name))  
        print object_ef
        object_cc = parent.findChild(QCheckBox, "%s_cc" % (object_name))
        print object_cc
        attrlist = [object_name, object_bool.isChecked(), object_sf.text(), object_ef.text(), object_cc]
        return attrlist
        # widget_list = self.camera_listwidget.findChildren(QCheckBox)  
        # for widget in widget_list :  
        #     print widget.objectName()
    def get_attr_up(self, checkbox) :  
        parent = checkbox
        object_name = parent.name
        print object_name
        object_bool = parent.findChild(QCheckBox, "%s_rc" % (object_name))  
        print object_bool
        object_sf = parent.findChild(QLineEdit, "%s_sf" % (object_name))  
        print object_sf
        object_ef = parent.findChild(QLineEdit, "%s_ef" % (object_name))  
        print object_ef
        object_cc = parent.findChild(QCheckBox, "%s_cc" % (object_name))
        print object_cc
        attrlist = [object_name, object_bool.isChecked(), object_sf.text(), object_ef.text(), object_cc]
        return attrlist


    def get_refNode_info(self, lst) :  
        SA.get_nodeInfo(self.basepath, self.asset_dict)


class list_iterm(QWidget) :  
    def __init__(self, new_name, new_type) :  
        super(list_iterm, self).__init__()
        self.name = new_name
        self.type = new_type
        self.setupUI()
        self.setObjectName("%s_w" % (self.name))

    def setupUI(self):  
        self.checkbox = QCheckBox()
        self.checkbox.setObjectName("%s_cb" %(self.name))
        self.name_label = QLineEdit(self.name)
        self.name_label.setMinimumWidth(110)
        # self.name_label.resize(40,80)

        self.name_label.setReadOnly(True)


        self.range_check = QCheckBox()
        self.range_check.setObjectName("%s_rc" %(self.name))
        self.start_label = QLabel("start")
        self.start_line = QLineEdit()
        self.start_line.setObjectName("%s_sf" %(self.name))
        self.end_label = QLabel("end")
        self.end_line = QLineEdit()
        self.end_line.setObjectName("%s_ef" %(self.name))

        self.checkbox.setStyleSheet("QCheckBox{color: rgb(0, 0, 0);background-color:#ACACAC}")
        self.range_check.setStyleSheet("QCheckBox{color: rgb(0, 0, 0);background-color:#ACACAC}")
        self.start_line.setStyleSheet("QLineEdit{color: rgb(0, 0, 0);background-color:#ACACAC}")
        self.end_line.setStyleSheet("QLineEdit{color: rgb(0, 0, 0);background-color:#ACACAC}")
        self.setLayout(QHBoxLayout())
        self.layout().addWidget(self.checkbox)
        self.layout().addWidget(self.name_label)
        self.layout().addWidget(self.range_check)
        self.layout().addWidget(self.start_label)
        self.layout().addWidget(self.start_line)
        self.layout().addWidget(self.end_label)
        self.layout().addWidget(self.end_line)
        if self.type == "model" :  
            self.cloth_cb = QCheckBox()
            self.cloth_cb.setObjectName("%s_cc" %(self.name))
            self.cloth_label = QLabel("Cloth")
            self.cloth_cb.setStyleSheet("QCheckBox{color: rgb(0, 0, 0);background-color:#00B54B}")
            self.cloth_label.setStyleSheet("QLabel{color: rgb(0, 0, 0);background-color:#00B54B}")
            self.layout().addWidget(self.cloth_label)
            self.layout().addWidget(self.cloth_cb)
        else :  
            pass

    def getType(self) :  
        return self.__class__()
class file_dialog(QFileDialog) :  
    def __init__(self, new_name) :  
        super(file_dialog, self).__init__()
        self.name = new_name
        self.setWindowTitle("%s" % (self.name))

def main() :  
    a = aaa()  
    reload(SA)
    a.show()  